from flask import request, jsonify
from flask import session

from info import constants
from info.models import News, Category,User
from info.modules.index import index_blu
from flask import render_template
from flask import current_app,g

from info.response_code import RET
from info.utils.common import user_login_data

@index_blu.route('/')
@user_login_data
def index():
    # return render_template("news/index.html")
    # logging.log(logging.D   EBUG, "This is a debug log.")
    # logging.log(logging.INFO, "This is a info log.")
    # logging.log(logging.WARNING, "This is a warning log.")
    # logging.log(logging.ERROR, "This is a error log.")
    # logging.log(logging.CRITICAL, "This is a critical log.")

    # 修改配置改变输出内容
    # logging.basicConfig(level=logging.DEBUG)
    # 查看当前已经登陆的用户
    user = g.user

    # 查询点击排行的咨询列表
    news_list = None

    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 获取新闻咨询的分类信息
    categories = Category.query.all()

    return render_template(
        "news/index.html",
        user=user,
        news_list=news_list,
        categories=categories
    )

@index_blu.route("/news_list")
def new_list():
    """根据分类ID获取新闻资讯列表"""
    # 1.获取参数[cid,当前页码,分页数量]
    cid = request.args.get("cid")
    page = request.args.get("page",1)
    per_page = request.args.get("per_page",constants.HOME_PAGE_MAX_NEWS)
    # 校验参数
    if not cid:
        return jsonify(errno=RET.DATAERR,errmsg="缺少参数")
    # 根据cid获取数据
    try:
        # 如果查询的是最新的新闻资讯,则获取的必须是所有分类下的信息
        filters = []
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
        if cid != 1:
            filters.append(News.category_id==cid)
        pagination =News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="无效参数")
    page = pagination.page
    # 获取当前页面中所有数据,是一个list数据,成员是news模型对象
    new_list = pagination.items
    pages = pagination.pages

    # 数据重构[把数据的格式进行调增为需要的格式]
    new_li = []
    for news in new_list:
        new_li.append(news.to_basic_dict()) # 把对象转换成字典结构
    # 返回数据
    return jsonify(errno=RET.OK,errmsg="OK",
                   cid =cid,
                   current_page = page,
                   pages = pages,
                   news_list = new_li
                   )

# 在浏览器访问网站的时候，都会自动到服务器的根目录下访问一个 favicon.ico 的网站图标文件
@index_blu.route("/favicon.ico")
def favicon():
    # current_app.send_static_file 的作用，读取静态资源目录下的文件内容
    return current_app.send_static_file("news/favicon.ico")